/*
 * @Description: js-sdk for cess storage
 * @Autor: cess lab
 */
const { Keyring } = require("@polkadot/api");

module.exports = class ControlBase {
  constructor(ss58Format) {
    this.ss58Format = ss58Format;
    this.keyring = new Keyring({ type: "sr25519", ss58Format });
  }
  authSign(mnemonic, msg) {
    let kr = this.keyring;
    const pair = kr.createFromUri(mnemonic);
    kr.setSS58Format(this.ss58Format);
    const publicKeyU8A = pair.publicKey;
    const ss58 = pair.address;
    const signU8A = pair.sign(msg);
    const publicKeyStr = util.uint8ArrayToHex(publicKeyU8A);
    const signStr = util.uint8ArrayToHex(signU8A);
    return {
      mnemonic,
      msg,
      publicKeyU8A,
      publicKeyStr,
      signU8A,
      signStr,
      ss58,
    };
  }

  formatAccountId(accountId32) {
    if (!accountId32 || accountId32.length == 64) {
      return accountId32;
    }
    const pair = this.keyring.addFromAddress(accountId32);
    this.keyring.setSS58Format(this.ss58Format);
    return pair.address;
  }
};
